package org.career.pdung.manager;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.career.pdung.domain.User;
import org.career.pdung.serviceImpl.UserServiceImpl;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
@SuppressWarnings({ "deprecation" })
public class UserAuthenticationManager implements AuthenticationManager {

	protected static Logger logger = Logger.getLogger("service");
	@Resource(name="passwordEncoder")
	private Md5PasswordEncoder passwordEncoder;
	@Resource(name="userServiceImpl")
	private UserServiceImpl userServiceImpl;
	public Authentication authenticate(Authentication auth) throws AuthenticationException {
		final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		User user = null;
		logger.debug("Performing custom authentication");
		try {
			List<User> listUser = userServiceImpl.getUserByEmail(auth.getName());
			user = listUser.get(0);
			if(user.getPassWord().isEmpty()){
				logger.debug("log in without password");
				authorities.add(new GrantedAuthorityImpl(user.getRoles()));
				return new UsernamePasswordAuthenticationToken( auth.getName(), auth.getCredentials(),authorities);
			}
			if (! user.getPassWord().equals(passwordEncoder.encodePassword( (String)auth.getCredentials(),null))) {
				logger.error("Wrong password!");
				throw new BadCredentialsException("Wrong password!");
			}
			
		} catch (Exception e) {
			logger.error("User does not exists!");
			throw new BadCredentialsException("User does not exists!");
		}				
			logger.debug("User details are good and ready to go");
			authorities.add(new GrantedAuthorityImpl(user.getRoles()));
			return new UsernamePasswordAuthenticationToken( auth.getName(), auth.getCredentials(),authorities);
	}

	
	
}
